package com.freecloud.javabasics.thread.threadlocal;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: maomao
 * @Date: 2021/8/31 9:09 上午
 */
public class ThreadLocalPool {

    public static void main(String[] args) {
        ThreadPoolExecutor executorService =
            new ThreadPoolExecutor(3, 20, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

        for (int i = 0; i < 100; i++) {
            executorService.submit(new TestTask("task-" + i, executorService));
        }
        executorService.shutdown();
    }

    public static class TestTask implements Runnable {
        private ThreadLocal<String> local = new ThreadLocal<>();
        private String name;
        private ThreadPoolExecutor executorService;

        public TestTask(String name, ThreadPoolExecutor executorService) {
            this.name = name;
            local.set(name);
            this.executorService = executorService;
            //System.out.println(String.format("constructor[%s] name : %s local: %s", Thread.currentThread().getName(), this.name,this.local.get()));
        }

        @Override
        public void run() {
            System.out.println(executorService);

            System.out.println(
                String.format("run(1) %s name : %s local: %s", Thread.currentThread().getName(), this.name,
                    this.local.get()));
            this.local.set(this.name);
            System.out.println(
                String.format("run(2) %s name : %s local: %s", Thread.currentThread().getName(), this.name,
                    this.local.get()));
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
